<?php
namespace app\api\controller;

use think\Controller;
use app\common\model\Video as VideoModel;

class Video extends Controller
{
    /**
     * 获取视频列表
     * @param int $page 页码
     * @param int $limit 每页数量
     * @param int $category_id 分类ID
     * @return json
     */
    public function list()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $category_id = input('category_id/d', 0);

        $where = ['status' => 1];
        if ($category_id > 0) {
            $where['category_id'] = $category_id;
        }

        $list = VideoModel::with(['user', 'category'])
            ->where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select();
            
        $count = VideoModel::where($where)->count();

        return json([
            'code' => 1,
            'data' => [
                'list' => $list,
                'total' => $count,
                'last_page' => ceil($count / $limit)
            ]
        ]);
    }

    /**
     * 获取视频详情
     * @param int $id 视频ID
     * @return json
     */
    public function detail()
    {
        $id = input('id/d', 0);
        if (!$id) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }

        $video = VideoModel::with(['user', 'category'])->find($id);
        if (!$video || $video->status != 1) {
            return json(['code' => 0, 'msg' => '视频不存在']);
        }

        // 增加浏览次数
        $video->setInc('views');

        return json(['code' => 1, 'data' => $video]);
    }

    /**
     * 上传视频
     * @param file $file 视频文件
     * @param string $title 视频标题
     * @param string $description 视频描述
     * @param int $category_id 分类ID
     * @return json
     */
    public function upload()
    {
        $user_id = session('user_id');
        if (!$user_id) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }

        $file = $this->request->file('file');
        if (!$file) {
            return json(['code' => 0, 'msg' => '请选择视频文件']);
        }

        $upload = new \app\common\service\Upload();
        $result = $upload->video($file);

        if ($result['code'] != 1) {
            return json(['code' => 0, 'msg' => $result['msg']]);
        }

        $data = $this->request->post();
        $data['user_id'] = $user_id;
        $data['video_url'] = $result['data']['url'];
        $data['status'] = 0; // 待审核

        if (VideoModel::create($data)) {
            return json(['code' => 1, 'msg' => '上传成功，请等待审核']);
        }
        return json(['code' => 0, 'msg' => '上传失败']);
    }
} 